package com.zmm.study.blog.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * description:
 * name MyElasticSearchConfig
 *
 * @author Zebulon
 * date By 2022-01-20 17:04:38
 */
@Configuration
public class MyElasticSearchConfig {

    @Value("${search.ip}")
    private String ip;

    @Value("${search.port}")
    private Integer port;

    @Value("${search.user.name}")
    private String userName;

    @Value("${search.user.password}")
    private String password;



    public static final RequestOptions COMMON_OPTIONS;
    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        /** builder.addHeader("Authorization", "Bearer " + TOKEN)
         builder.setHttpAsyncResponseConsumerFactory(
         new HttpAsyncResponseConsumerFactory
         .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024))*/
        COMMON_OPTIONS = builder.build();
    }



    @Bean
    public RestHighLevelClient restHighLevelClient(){

        HttpHost host = new HttpHost(ip,port, HttpHost.DEFAULT_SCHEME_NAME);

        RestClientBuilder builder = RestClient.builder(host);

        if (!StringUtils.isEmpty(userName)) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
            builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
        }
        /**
         * 通过密码来连接 es
         * CredentialsProvider credentialsProvider = new BasicCredentialsProvider()
         * credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("用户名", "密码"))
         * builder.setHttpClientConfigCallback(f->f.setDefaultCredentialsProvider(credentialsProvider))
         */
        RestHighLevelClient client = new RestHighLevelClient(builder);

        return client;
    }
}
